<template>
    <div class="water-data-container">
        <!-- 年份选择器 -->
        <div class="data-selector">
            <label class="fs-xs" style="white-space: nowrap;">选择统计年份:</label>
            <select v-model="selectedYear" @change="handleYearChange">
                <option v-for="year in availableYears" :value="year" :key="year">
                    {{ year }}年
                </option>
            </select>

            <!-- 区域选择器（优化联动逻辑） -->
            <label class="fs-xs" style="white-space: nowrap;" v-show="selectedYear">选择展示区域:</label>
            <select v-model="selectedDistrict" v-show="selectedYear">
                <option value="">-- 选择其他区域 --</option>
                <option v-for="district in otherDistricts" :value="district.区名" :key="district.区名">
                    {{ district.区名 }}
                </option>
            </select>
        </div>

        <!-- 数据总览卡片 -->
        <div class="overview-card dark-card" v-show="currentData.length">
            <h3 class="dark-title">天津市水资源配置总览 ({{ selectedYear }}年)</h3>
            <div class="stats-grid">
                <div class="stat-card dark-stat">
                    <div class="stat-value">{{ totalDemand.toFixed(2) }}亿m³</div>
                    <div class="stat-label">总需水量</div>
                </div>
                <div class="stat-card dark-stat">
                    <div class="stat-value">{{ totalSupply.toFixed(2) }}亿m³</div>
                    <div class="stat-label">总供水量</div>
                </div>
                <div class="stat-card dark-stat" :class="shortage > 0 ? 'shortage' : 'balanced'">
                    <div class="stat-value">{{ shortage > 0 ? shortage.toFixed(2) : '0' }}亿m³</div>
                    <div class="stat-label">{{ shortage > 0 ? '缺水量' : '供需平衡' }}</div>
                </div>
            </div>
        </div>

        <!-- 区域数据展示 -->
        <div class="district-table" v-show="currentData.length">
            <h3 class="dark-title">各区水资源配置详情</h3>
            <div class="vertical-table-container">
                <!-- 常驻展示：市内六区 -->
                <DistrictCard v-if="hasDistrict('市内六区')" :district="getDistrict('市内六区')" />

                <!-- 动态展示：通过选择器切换的区域 -->
                <DistrictCard v-if="selectedDistrict" :district="getDistrict(selectedDistrict)" />
            </div>
        </div>

        <!-- 图表展示 -->
        <div class="charts-container" v-show="currentData.length">
            <h3 class="dark-title">水资源配置分析</h3>
            <div class="chart-row">
                <div class="chart-card dark-card">
                    <div ref="demandChartRef" class="echart-container"></div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import waterData from '@/js/PredictDispatching.json';
import DistrictCard from './DistrictCard.vue';

// 新增：年份管理
const selectedYear = ref(''); // 初始不选中
const availableYears = ref([]); // 动态获取所有可用年份
const currentData = ref([]);

// 区域选择状态
const selectedDistrict = ref('');
const otherDistricts = ref([]);

// 计算属性
const totalDemand = ref(0);
const totalSupply = ref(0);
const shortage = ref(0);

// 图表引用
const demandChartRef = ref(null);

// 初始化数据
onMounted(() => {
    // 提取所有可用年份
    availableYears.value = Object.keys(waterData).sort((a, b) => b - a); // 倒序排列

    // 初始选择最近一年
    if (availableYears.value.length) {
        selectedYear.value = availableYears.value[0];
    }
});

// 年份切换处理
watch(selectedYear, (newYear) => {
    if (!newYear) return; // 未选择年份时清空数据

    currentData.value = waterData[newYear] || [];
    updateOtherDistricts();
    calculateTotals();
    nextTick(createDemandChart);
});



// 计算其他区域列表
const updateOtherDistricts = () => {
    otherDistricts.value = currentData.value.filter(d => d.区名 !== '市内六区');
};

// 计算总数据
const calculateTotals = () => {
    const demand = currentData.value.reduce((sum, d) =>
        sum + parseFloat(d.需水.总需水), 0);

    const supply = currentData.value.reduce((sum, d) =>
        sum + parseFloat(d.供水.总供水), 0);

    const shortageVal = demand > supply ? demand - supply : 0;

    totalDemand.value = demand;
    totalSupply.value = supply;
    shortage.value = shortageVal;
};

// 辅助函数：检查区域是否存在
const hasDistrict = (name) =>
    currentData.value.some(d => d.区名 === name);

// 辅助函数：获取区域数据
const getDistrict = (name) =>
    currentData.value.find(d => d.区名 === name) || {};

// 图表创建函数（优化数据获取）
const createDemandChart = () => {
    console.log(6)
    const chartDom = demandChartRef.value;
    if (!chartDom || !currentData.value.length) return;

    // 计算当前选择区域的需水结构（如果需要按区域过滤）
    // 目前逻辑是计算全部区域，如需按区域展示需调整这里的数据源
    const targetData = selectedDistrict.value
        ? [getDistrict(selectedDistrict.value)]
        : currentData.value;

    const demandTypes = ['生活需水', '农业需水', '工业需水', '生态需水'];
    const demandTotals = demandTypes.map(type =>
        targetData.reduce((sum, d) =>
            sum + parseFloat(d.需水[type]), 0)
    );

    const myChart = echarts.init(chartDom, 'dark');
    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(30, 30, 30, 1.0)',
            textStyle: {
                color: '#fff'
            }
        },
        legend: {
            orient: 'vertical',
            right: 'right',
            textStyle: {
                color: '#ccc'
            },
            data: ['生活用水', '农业用水', '工业用水', '生态用水']
        },
        series: [
            {
                name: '需水结构',
                type: 'pie',
                radius: '65%',
                center: ['40%', '50%'],
                data: [
                    { value: demandTotals[0], name: '生活用水' },
                    { value: demandTotals[1], name: '农业用水' },
                    { value: demandTotals[2], name: '工业用水' },
                    { value: demandTotals[3], name: '生态用水' }
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.0)'
                    }
                },
                label: {
                    color: '#ccc'
                }
            }
        ]
    };

    myChart.setOption(option);
    window.addEventListener('resize', () => myChart.resize());
};

// 监听数据变化
watch(currentData, () => {
    if (currentData.value.length) {
        calculateTotals();
        nextTick(createDemandChart);
    }
}, { deep: true });

watch(selectedDistrict, (newVal) => {
    // 区域切换时需要更新的逻辑
    nextTick(() => {
        // 这里可以添加区域切换时需要执行的操作
        // 例如：重新计算图表数据或更新其他组件
        createDemandChart(); // 直接触发图表更新
    });
});
</script>


<style scoped lang="scss">
@use "sass:math";

$dark-bg: #1a1a1a;
$card-bg: #222;
$highlight-bg: #2a2a2a;
$text-primary: #e0e0e0;
$text-secondary: #aaa;
$text-highlight: #fff;
$border-color: #333;
$shadow-color: rgba(0, 0, 0, 0.3);
$shortage-color: #ef5350;
$balanced-color: #66bb6a;

// 基础尺寸调整
$spacing-unit: 0.5rem; // 减小基础间距单位
$card-padding: 0.875rem; // 减小卡片内边距
$chart-height: 8rem; // 减小图表高度

.water-data-container {
    width: 100%;
    padding: $spacing-unit;
    font-family: 'Arial', sans-serif;
    color: $text-primary;
    background-color: $dark-bg;
    border-radius: 0.5rem;
    box-sizing: border-box;
    height: 98%;

    ::-webkit-scrollbar-track {
        background: $card-bg;
    }

    ::-webkit-scrollbar-thumb {
        background: #444;
        border-radius: 0.25rem;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: #555;
    }
}

.data-selector {
    margin-bottom: $spacing-unit;
    display: flex;
    align-items: center;

    label {
        color: $text-primary;
    }

    select {
        padding: 0.3125rem 0.625rem;
        background-color: $highlight-bg;
        color: $text-primary;
        border: 1px solid #444;
        border-radius: 0.25rem;
        outline: none;
        transition: all 0.2s;

        &:hover {
            border-color: #555;
        }

        &:focus {
            box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.25);
        }
    }
}

.dark-card {
    background-color: $card-bg;
    border-radius: 0.5rem;
    padding: $card-padding;
    margin-bottom: $spacing-unit;
    box-shadow: 0 2px 8px $shadow-color;
    transition: transform 0.2s, box-shadow 0.2s;

    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px $shadow-color;
    }
}

.dark-title {
    color: $text-highlight;
    margin-bottom: 0.625rem;
    font-size: 1rem;
    font-weight: 600;
}

.dark-subtitle {
    color: #ddd;
    margin-bottom: 0.5rem;
    font-size: 0.9375rem;
    font-weight: 500;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: $spacing-unit;

    @media (max-width: 768px) {
        grid-template-columns: 1fr;
    }
}

.dark-stat {
    background-color: $highlight-bg;
    border-radius: 0.375rem;
    padding: 0.625rem;
    text-align: center;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    transition: all 0.2s;

    &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    }
}

.stat-value {
    font-size: 1.125rem;
    font-weight: bold;
    margin-bottom: 0.1875rem;
}

.stat-label {
    color: $text-secondary;
    font-size: 0.75rem;
}

.shortage {
    background-color: rgba(183, 28, 28, 0.15);
    color: $shortage-color;
}

.balanced {
    background-color: rgba(46, 125, 50, 0.15);
    color: $balanced-color;
}

.district-table {
    margin-bottom: $spacing-unit;
}

.table-container {
    overflow-x: auto;
}

.dark-table {
    width: 100%;
    border-collapse: collapse;

    th,
    td {
        border: 1px solid $border-color;
        padding: 0.375rem;
        text-align: center;
        transition: background-color 0.2s;
        font-size: 0.875rem;
    }

    th {
        background-color: $highlight-bg;
        font-weight: bold;
        color: $text-highlight;
    }

    tr:nth-child(even) {
        background-color: #1e1e1e;
    }

    tr:hover {
        background-color: #242424;
    }
}

.shortage-text {
    color: $shortage-color;
    font-weight: bold;
}

.balanced-text {
    color: $balanced-color;
}

.charts-container {
    margin-bottom: $spacing-unit;
}

.chart-card {
    height: $chart-height;

    @media (max-width: 992px) {
        height: 12rem;
    }
}

.echart-container {
    width: 100%;
    height: 100%;
}

// 竖版表格样式优化高度
.vertical-table-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(16.25rem, 1fr));
    gap: $spacing-unit;

    @media (max-width: 768px) {
        grid-template-columns: 1fr;
    }
}

.district-card {
    background-color: $card-bg;
    border-radius: 0.5rem;
    padding: 0.75rem;
    box-shadow: 0 2px 8px $shadow-color;
    transition: all 0.2s;

    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px $shadow-color;
    }
}

.district-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.5rem;

    h4 {
        color: $text-highlight;
        font-size: 0.9375rem;
        margin: 0;
    }
}

.supply-status {
    padding: 0.0625rem 0.375rem;
    border-radius: 0.25rem;
    font-size: 0.75rem;
}

.water-stats {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.stat-group {
    background-color: $highlight-bg;
    border-radius: 0.375rem;
    padding: 0.5rem;
}

.stat-title {
    color: #ddd;
    font-weight: bold;
    margin-bottom: 0.375rem;
    font-size: 0.875rem;
}

.stat-row {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 0.25rem;
}

.stat-item {
    text-align: center;
    padding: 0.25rem;
    border-radius: 0.25rem;
    transition: all 0.2s;

    &:hover {
        background-color: rgba(255, 255, 255, 0.05);
    }
}

.stat-label {
    color: $text-secondary;
    font-size: 0.6875rem;
    margin-bottom: 0.125rem;
}

.stat-value {
    color: $text-primary;
    font-size: 0.8125rem;
}

.stat-item.total {
    .stat-label {
        color: #ccc;
    }

    .stat-value {
        font-weight: bold;
    }
}

// 新增样式：其他区预览列表
.other-districts-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(16.25rem, 1fr));
    gap: $spacing-unit;
    margin-top: $spacing-unit;
}

.district-preview {
    background-color: $card-bg;
    border-radius: 0.5rem;
    padding: 0.75rem;
    box-shadow: 0 2px 8px $shadow-color;
    cursor: pointer;

    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px $shadow-color;
    }
}

/* 新增年份选择器样式 */
.data-selector {
    /* 保持原有样式 */
    display: flex;
    align-items: center;
    gap: 0.3rem;
    /* 增加选择器间距 */

    select {
        /* 保持原有样式 */
        min-width: 90px;
        /* 固定选择器宽度 */
    }
}

/* 响应式调整 */
@media (max-width: 768px) {
    .data-selector {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.1rem;
    }
}
</style>